package com.ruoyi.business.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.ruoyi.business.domain.ResearchPlan;
import com.ruoyi.business.domain.Task;
import com.ruoyi.business.domain.TaskUser;
import com.ruoyi.business.enums.UserSurveyStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author liutao
 * @version 1.0
 * @description: TODO
 * @date 2024/5/27 19:07
 */
@Slf4j
@Service
public class TimerTaskService {
    @Resource
    private IResearchPlanService researchPlanService;

    @Resource
    private ITaskService taskService;

    @Resource
    private ITaskUserService taskUserService;

    public void finishPlan() {
        List<ResearchPlan> planList = researchPlanService.selectEndPlan();
        if (CollUtil.isNotEmpty(planList)) {
            for (ResearchPlan researchPlan : planList) {
                List<Task> taskList = taskService.list(Wrappers.lambdaQuery(Task.class)
                        .eq(Task::getResearchPlanId, researchPlan.getId()));
                if (CollUtil.isEmpty(taskList)) {
                    continue;
                }
                for (Task task : taskList) {
                    List<TaskUser> taskUsers = taskUserService.list(Wrappers.lambdaQuery(TaskUser.class)
                            .eq(TaskUser::getTaskId, task.getId()));
                    if (CollUtil.isEmpty(taskUsers)) {
                        continue;
                    }
                    List<TaskUser> updateList = Lists.newArrayList();
                    for (TaskUser taskUser : taskUsers) {
                        TaskUser updateTaskUser = new TaskUser();
                        updateTaskUser.setId(taskUser.getId());
                        updateTaskUser.setSurveyStatus(UserSurveyStatus.COMPLETED.getKey());
                        updateList.add(updateTaskUser);
                    }
                    taskUserService.updateBatchById(updateList);
                }
            }
        }
    }
}
